package start.fly.test.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import start.fly.test.database.linksql;

public class upfile extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String username = (String)session.getAttribute("username");
		File file ;
		   int maxFileSize = 5000 * 1024;
		   int maxMemSize = 5000 * 1024;
		   ServletContext context = this.getServletContext();
		   String filePath = context.getInitParameter("file-upload");
		   // 验证上传内容了类型
		   String contentType = request.getContentType();
		   if ((contentType.indexOf("multipart/form-data") >= 0)) {

		      DiskFileItemFactory factory = new DiskFileItemFactory();
		      // 设置内存中存储文件的最大值
		      factory.setSizeThreshold(maxMemSize);
		      // 本地存储的数据大于 maxMemSize.
		      factory.setRepository(new File("d:\\temp"));

		      // 创建一个新的文件上传处理程序
		      ServletFileUpload upload = new ServletFileUpload(factory);
		      // 设置最大上传的文件大小
		      upload.setSizeMax( maxFileSize );
		      try{ 
		         // 解析获取的文件
		         List fileItems = upload.parseRequest(request);

		         // 处理上传的文件
		         Iterator i = fileItems.iterator();

		         out.println("<html>");
		         out.println("<head>");
		         out.println("<title>JSP File upload</title>");  
		         out.println("</head>");
		         out.println("<body>");
		         while ( i.hasNext () ) 
		         {
		            FileItem fi = (FileItem)i.next();
		            if ( !fi.isFormField () )	
		            {
		            // 获取上传文件的参数
		            String fieldName = fi.getFieldName();
		            String fileName = fi.getName();
		            boolean isInMemory = fi.isInMemory();
		            long sizeInBytes = fi.getSize();
		            // 写入文件
		            if( fileName.lastIndexOf("\\") >= 0 ){
		            file = new File( filePath , 
		            fileName.substring( fileName.lastIndexOf("\\"))) ;
		            }else{
		            file = new File( filePath ,
		            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
		            }
		            fi.write( file ) ;
		            out.println("Uploaded Filename: " + filePath +",filename:"+ 
		            fileName + "<br>");
		            
		            System.out.println("Uploaded Filename: " + filePath);
		            System.out.println("filename:"+fileName);
		            //String url = "http://zhidao.baidu.com/question/147458024.html";  
		            //取得最后一个/的下标  
		            int index = fileName.lastIndexOf("\\");  
		            //将字符串转为字符数组  
		            char[] ch = fileName.toCharArray();  
		            //根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串  
		            String lastString = String.copyValueOf(ch, index + 1, ch.length - index - 1);  
		            System.out.println(lastString);
		            System.out.println(username);
		            linksql ls = new linksql();
		            ls.link();
			         try{
			        	 ls.rs1 = ls.st.executeQuery("select count(*) from userinfo where username='"+username+"'");
			        	 ls.rs1.next();
			        	 if(ls.rs1.getInt(1) != 0){
			        		 System.out.println("1");
			        		 ls.rs = ls.st.executeUpdate("update userinfo set img='"+lastString+"' where username='"+username+"'");
			        	 }else{
			        		 System.out.println("2");
			        		 ls.rs = ls.st.executeUpdate("insert into userinfo (username,img) values('"+username+"','"+lastString+"')"); 
			        	 }
			         }catch(Exception e){
			        	 e.printStackTrace();
			         }
			         out.println("<a href='user/detail.jsp'>返回继续注册</a>");
		            }
		         }
		         response.sendRedirect("user/detail.jsp");
		         /*session.setAttribute("situation", "success");
		         response.sendRedirect("info.jsp");*/
		         out.println("</body>");
		         out.println("</html>");
		      }catch(Exception ex) {
		         System.out.println(ex);
		      }
		   }else{
			   /*session.setAttribute("situation", "fail");
			   response.sendRedirect("info.jsp");*/
		      out.println("<html>");
		      out.println("<head>");
		      out.println("<title>Servlet upload</title>");  
		      out.println("</head>");
		      out.println("<body>");
		      out.println("<p>No file uploaded</p>"); 
		      out.println("</body>");
		      out.println("</html>");
		   }
		   

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);

	}

}
